﻿Option Strict On

Imports QueueManager.Helper.CRM
Imports QueueManager.Helper
Imports System.Configuration

Partial Class ClientInformation
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim objCrm As New CRMHelper
        Dim objName As NameStruct
        Dim objEMail As email

        'Verify that the paramaters are there
        If String.IsNullOrEmpty(Request.QueryString("key")) OrElse String.IsNullOrEmpty(Request.QueryString("t")) OrElse String.IsNullOrEmpty(Request.QueryString("s")) Then
            'If not, hide all fields.
            ctlHeader.Visible = False
            cmdSubmit.Visible = False
            ctlContainer.Visible = False
            ctlWelcomeText.Visible = False
            ctlRequiredInfoText.Visible = True
            Exit Sub
        End If

        If Not IsPostBack Then

            'Disable on postback
            cmdSubmit.Attributes.Add("onclick", "document.body.style.cursor = 'wait'; this.disabled = true; " & ClientScript.GetPostBackEventReference(cmdSubmit, String.Empty) & ";")

            'Retrieve the e-mail
            objEMail = GetEMail()

            If objEMail IsNot Nothing Then

                txtEMail.Text = objEMail.from(0).addressused

                'Now try to work out the first and last name
                If Not String.IsNullOrEmpty(objEMail.submittedby) Then

                    'Find and get the name from the string (which should be "FirstName LastName <name@domain.com>", but you never know).
                    objName = objCrm.ResolveNames(objEMail.submittedby)

                    txtFirstName.Text = objName.FirstName
                    txtLastName.Text = objName.LastName

                    'Set focus
                    If txtFirstName.Text = "" Then
                        txtFirstName.Focus()
                    ElseIf txtLastName.Text = "" Then
                        txtLastName.Focus()
                    Else
                        txtCompany.Focus()
                    End If

                Else
                    'Set focus to first textbox
                    txtFirstName.Focus()
                End If

                'If cookies are support then store in session to avoid having to retrieve it again on postback
                If Request.Browser.Cookies Then
                    Session("email") = objEMail
                End If

            Else
                'Zero or more e-mails returned, display message and bail out
                cmdSubmit.Visible = False
                ctlContainer.Visible = False
                ctlWelcomeText.Visible = False
                ctlNotFoundText.Visible = True
            End If
        End If

    End Sub

    Protected Sub cmdSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click

        Dim objCrm As New CRMHelper
        Dim objEMail As email
        Dim objContact As contact
        Dim objID As Guid

        'Bail out if not valid
        If Not Me.IsValid Then
            Exit Sub
        End If

        'Get the email using either session or from the server again
        If Session("email") Is Nothing Then
            objEMail = GetEMail()
        Else
            objEMail = CType(Session("email"), email)
        End If

        'Hide fields if we couldn't retrieve the e-mail
        If objEMail Is Nothing OrElse CType(Session("submitted"), String) = objEMail.activityid.Value.ToString Then
            ctlHeader.Visible = False
            cmdSubmit.Visible = False
            ctlContainer.Visible = False
            ctlWelcomeText.Visible = False
            ctlRequiredInfoText.Visible = True
            Exit Sub
        End If

        'Create a new contact using the information provided
        objContact = New contact

        'Set properties, this can be modified to the fields you need.
        objContact.firstname = txtFirstName.Text
        objContact.lastname = txtLastName.Text
        objContact.mobilephone = txtMobile.Text
        objContact.emailaddress1 = txtEMail.Text
        objContact.jobtitle = txtJobTitle.Text
        objContact.description = "Information created by the user. Company name specified: " & txtCompany.Text

        'Alternative e-mail
        If txtAltEMail.Text <> "" Then
            objContact.emailaddress2 = txtAltEMail.Text
        End If

        'Attempt to resolve the parent account automatically
        If ConfigurationManager.AppSettings("resolveparent") = "true" Then
            objCrm.ResolveParentAccount(objContact, _
                                        txtEMail.Text, _
                                        ConfigurationManager.AppSettings("resolveparent-notify"), _
                                        ConfigurationManager.AppSettings("resolveparent-from"))
        End If

        'Create contact
        objID = objCrm.GetCrmService.Create(objContact)

        'Update email
        With objEMail.from(0)
            .partyid = New Lookup
            .partyid.type = EntityName.contact.ToString
            .partyid.Value = objID
        End With

        'Reset tracking token
        objEMail.trackingtoken = Nothing

        'Update e-mail
        objCrm.GetCrmService.Update(objEMail)

        'Reoute the e-mail back to the queue for processing
        objCrm.RouteEMail(objEMail, Request.QueryString("s"), Request.QueryString("t"))

        'Modify texts
        cmdSubmit.Visible = False
        ctlContainer.Visible = False
        ctlWelcomeText.Visible = False
        ctlThanksText.Visible = True
        Session("submitted") = objEMail.activityid.Value.ToString

    End Sub

    Private Function GetEMail() As email

        Dim objCRM As New CRMHelper
        Dim objQuery As QueryExpressionHelper
        Dim objEntities() As BusinessEntity
        Dim objEMail As email

        'Get the e-mail using the token submitted
        objQuery = New QueryExpressionHelper(EntityName.email)

        objQuery.Columns.AddColumns("from", "submittedby", "activityid")
        objQuery.Criteria.FilterOperator = LogicalOperator.And
        objQuery.Criteria.Conditions.AddCondition("trackingtoken", ConditionOperator.Equal, Request("key"))

        objEntities = objCRM.GetCrmService.RetrieveMultiple(objQuery.Query).BusinessEntities

        If objEntities.Length = 1 Then
            'Get the e-mail address
            objEMail = CType(objEntities(0), email)

            'If partyid is set the contact has already been updated
            If objEMail.from(0).partyid Is Nothing Then
                Return objEMail
            Else
                Return Nothing
            End If

        Else
            Return Nothing
        End If

    End Function

    Protected Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Error

        LogHelper.Log("Error rendering UpdateClientInformation.", Context.Error, LogHelper.LogType.Exception)

        ctlHeader.Visible = False
        cmdSubmit.Visible = False
        ctlContainer.Visible = False
        ctlWelcomeText.Visible = False
        ctlRequiredInfoText.Visible = False
        ctlError.Visible = True

    End Sub

End Class
